package sg.edu.nus.iss.vmcs.machinery;

import sg.edu.nus.iss.vmcs.system.*;
import sg.edu.nus.iss.vmcs.util.*;
import sg.edu.nus.iss.vmcs.store.*;

public class MachineryController {

	public MainController mainCtrl;
	public StoreService storeService;

	private MachinerySimulatorPanel ml;
	private Door door;

	public MachineryController(MainController mctrl) {
		mainCtrl = mctrl;		
	}

	public MainController getMainController() {
		return mainCtrl;
	}

	public void initialize() throws VMCSException {
		door = new Door();
		storeService = mainCtrl.getStoreService();
	}

	public void closeDown() {
		if (ml != null)
			ml.dispose();
	}

	/*
	 * Panel Operations
	 */

	public void displayMachineryPanel() {
		//SimulatorControlPanel scp = mainCtrl.getSimulatorControlPanel();
		if (ml == null)
			ml = new MachinerySimulatorPanel( this);
		try
		{
			mainCtrl.registerObservers(Store.CASH, ml);
			mainCtrl.registerObservers(Store.DRINK, ml);// register for observer
			ml.display();
		} catch (VMCSException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // register for observer
		
		//scp.setActive(SimulatorControlPanel.ACT_MACHINERY, false);
	}

	public void closeMachineryPanel() {
		if (ml == null)
			return;
		boolean ds = isDoorClosed();

		if (ds == false) {
			MessageDialog msg = new MessageDialog(ml,
					"Please Lock the Door before You Leave");
			msg.setVisible(true);
			return;
		}
		ml.dispose();
		//SimulatorControlPanel scp = mainCtrl.getSimulatorControlPanel();
		//scp.setActive(SimulatorControlPanel.ACT_MACHINERY, true);
	}

	/*
	 * Door operation
	 */

	public boolean isDoorClosed() {
		return door.isDoorClosed();
	}

	public void setDoorState(boolean state) {
		door.setState(state);
		displayDoorState();
	}

	/*
	 * Display operation
	 */

	public void displayDoorState() {
		if (ml == null)
			return;
		ml.setDoorState(door.isDoorClosed());
	}

	// update drink stock view;
	public void displayDrinkStock() throws VMCSException {
		if (ml == null)
			return;
		ml.getDrinksStoreDisplay().update();
	}

	// update coin stock view after transfer all cash;
	public void displayCoinStock() throws VMCSException {
		if (ml == null)
			return;
		ml.getCashStoreDisplay().update();
	}

	/*
	 * Interactions with the Store that need to update the display
	 */
	public void storeCoin(Coin c) throws VMCSException {
		storeService.storeCoin(c);
		if (ml != null)
			ml.getCashStoreDisplay().update();
	}

	public void dispenseDrink(int idx) throws VMCSException {
		storeService.dispenseDrink(idx);
		if (ml != null)
			ml.getCashStoreDisplay().update();

	}

	public void giveChange(int idx, int numOfCoins) throws VMCSException {
		storeService.giveChange(idx, numOfCoins);
		if (ml != null)
			ml.getCashStoreDisplay().update();
	}

}
